<?php
/**
 * Created by PhpStorm.
 * User: zhixuedong
 * Date: 2022/8/23
 * Time: 15:39
 */

namespace app\api\controller;


use app\project\service\AdvancePlanService;
use app\project\service\PublicService;
use think\Controller;
use think\Db;
use think\Exception;

class Advance extends Controller
{

    //获取推进计划类别
    public function problemTypeApi(){
        try{
            $where['status']    = 1;
            $pro_id             = empty($_POST['id'])?0:$_POST['id'];

            $common = new Common();
            $proDetail = Db::name("project_pro")->where("id",$pro_id)->field("id,library,plan_category,pid")->find();
            $library = empty($proDetail['library'])?0:$proDetail['library'];
            $type = 0;
            if($proDetail['plan_category'] == 1){
                $type = 20;
            }
            if($proDetail['plan_category'] == 2){
                $type = 21;
            }

            if($library==1){
                $library = 2;
            }

            //获取推进计划
            $parentWhere['library'] = ['like',"%".$library."%"];
            $parentWhere['pid'] = 0;
            $parentWhere['type'] = $type;
            $parentWhere['status'] = 1;
            $list = Db::name("project_type")->where($parentWhere)->order("sort asc,id desc")->select();

            $pro_id = empty($proDetail['pid'])?$pro_id:$proDetail['pid'];

            $listData = [];
            if($list){
                //获取推进计划子级
                foreach ($list as $k=>$v){
                    unset($childWhere);
                    $childWhere['library'] = ['like',"%".$library."%"];
                    $childWhere['pid'] = $v['id'];
                    $childWhere['status'] = 1;
                    $child = Db::name("project_type")->where($childWhere)->field("id,name")->order("sort asc,id desc")->select();
                    foreach ($child as $key=>$val){
                        //查询计划内容是否存在
                        $infoWhere['type_id'] = $val["id"];
                        $infoWhere['pro_id'] = $pro_id;
                        $info                       = $common->public_select("project_pro_advance_plan",$infoWhere,'id,time,color,status,content,duty_unit')->find();



                        $child[$key]['duty_unit'] = empty($info['duty_unit'])?"-":$info['duty_unit'];
                        $child[$key]['time'] = empty($info['time'])?"-":$info['time']; //计划时间
                        $child[$key]['color'] = isset($info['color'])?$info['color']:"-"; //旗子颜色
                        $child[$key]['is_shen'] = 0;  //是否需要审核
                        if (!empty($info)){
                            if($info['content']!='' & $info['status']==0){
                                $child[$key]["is_shen"] = 1;
                            }
                        }
                        $child[$key]['plan_id'] = empty($info['id'])?"-":$info['id'];  //推进计划id
                        //是否存在未审核的延期申请
                        unset($where);
                        $where['pro_id'] = $pro_id;
                        $where['type_id'] = $val['id'];
                        $where['status'] = 0;
                        $applyCount = PublicService::counService("project_pro_advance_apply",$where);
                        $child[$key]['applyCount'] = $applyCount; //申请延期数量

                        $child[$key]['title'] = $v['name'];
                        $listData[] = $child[$key];
                    }
                }
            }
            return buildSuccess($listData);
        }catch (Exception $e){
            return buildError($e->getMessage().$e->getLine(),202);
        }
    }


    //添加推进计划
    public function createPlan(){

        $common = new Common();
        $project = new Project();
        if(!empty($_POST['uid'])){
            $project_user = $common->testusername($_POST['uid']);
        }else{
            $project_user = $project->iflogin();
        }

        try{
            $proId = $_POST['pro_id'];


            $autoSumbit = 0;
            //判断是否是该项目负责人
            $proWhere['id'] = $proId;
            $proDetail = Db::name("project_pro")->where($proWhere)->find();
            $duty_person = explode(";",$proDetail['duty_person']);
            if(in_array($project_user['name'],$duty_person)){
                $autoSumbit = 1;
            }
            //判断是否是该项目负责人end

            $data['type_id'] = $_POST['type_id'];
            $data['pro_id'] = empty($proDetail['pid'])?$proId:$proDetail['pid'];
            $data['status'] = ['in',[0,1,2]];
            $detail = AdvancePlanService::detailService($data,1);

            $duty_unit = explode(";",$detail['duty_unit']);
            $Interfacea = new Interfacea();
            $thisDictionarie = $Interfacea->getDictionarie($project_user);
            if(in_array($thisDictionarie,$duty_unit)){
                $autoSumbit = 1;
            }

            if($autoSumbit==0){
                throw new Exception("您不是该项目的负责人&服务单位，不能进行操作");
            }

            if(!empty($detail)){
                // if($detail['status']==0){
                //     throw new Exception("该计划审核中，请勿重复添加");
                // }
                if($detail['status']==1){
                    throw new Exception("该计划已审核，不可修改");
                }


                if(!empty($detail['time'])){
                    if(empty($_POST['content'])){
                        throw new Exception("请输入汇报内容");
                    }
                }
                $data['status'] = 0;
                $data["id"] = $detail["id"];
            }else{
                $data["color"] = 0;


            }

            if(!empty($_POST["time"])){
                $data["time"]       = $_POST["time"] ??0;
                $nowTime = date("Y-m-d");
                $day = (strtotime($nowTime)-strtotime($data['time'])) / 86400;
                $actualsignTime = $proDetail['actualsignTime'];
                $plantime[343] = date("Y-m-d",strtotime("+3 Month",strtotime($actualsignTime)));
                $plantime[344] = date("Y-m-d",strtotime("+7 Month",strtotime($actualsignTime)));
                $plantime[350] = date("Y-m-d",strtotime("+31 Month",strtotime($actualsignTime)));
                if(!empty($plantime[$data['type_id']])){
                    $actualsignTime = $plantime[$data['type_id']];
                    if($data["time"]>$actualsignTime){
                        throw new Exception("基础开工时间不得大于".$actualsignTime);
                    }
                }
                $data["color"] = 0;
                if($day>=1){
                    $data["color"] = 2;
                }
                if($day>30){
                    $data["color"] = 3;
                }
                if($data['type_id']==343){
                    //拟开工时间
                    Db::name("project_pro")->where($proWhere)->update(['plan_onstream_time'=>$data["time"]]);
                    //实际开工时间
                    Db::name("project_pro")->where($proWhere)->update(['onstream_time'=>$data["time"]]);
                }
                if($data['type_id']==350){
                    //拟投产时间
                    Db::name("project_pro")->where($proWhere)->update(['planned_production_time'=>$data["time"]]);
                }
            }





            $content            = $_POST['content'] ?? '';
            $end_time           = $_POST['end_time'] ?? '';
            if(!empty($_POST['pic'])){
                $data['images'] = $_POST['pic'] ?? '';
            }

            if($end_time==null){
                $end_time = date("Y-m-d");
            }

            $data['content']    = $content;
            $data['start_time'] = $_POST['start_time'] ?? '';
            $data['end_time']   = $end_time;
            $data['addtime']    = date("Y-m-d H:i:s");
            $data['add_id']     = $project_user['id'];
            $data['code']    = $_POST['code'] ?? '';
            AdvancePlanService::saveService($data);
            return buildSuccess();
        }catch (Exception $e){
            return buildError($e->getMessage(),202,['line'=>$e->getLine()]);
        }
    }


    //推进计划详情
    public function problemInfo(){
        $common = new Common();
        $project = new Project();
        if(!empty($_POST['uid'])){
            $project_user = $common->testusername($_POST['uid']);
        }else{
            $project_user = $project->iflogin();
        }

        try{
            //判断是否有提交权限
            $where['id'] = $_POST['pro_id'];
            $detail = PublicService::detailService("project_pro",$where, 1);
            //责任人
            $leading_cadre = 0;
            if(strpos($detail['duty_person'],$project_user['name'])!==false){
                $leading_cadre = 1;
            }

            unset($where);
            $where["pro_id"]      = empty($detail['pid'])?$_POST['pro_id']:$detail['pid'];
            $where['type_id']     = empty($_POST['type_id'])?0:$_POST['type_id'];
            $data               = PublicService::detailService("project_pro_advance_plan",$where,1);
            $images = [];
            if(!empty($data['images'])){
                $images = explode(";",$data['images']);
            }
            $data['images'] = $images;

            $data['leading_cadre'] = $leading_cadre;
            return buildSuccess($data);
        }catch (Exception $e){
            return buildError($e->getMessage());
        }
    }

    //服务单位
    public function serviceInfo(){
        $common = new Common();
        $project = new Project();
        if(!empty($_POST['uid'])){
            $project_user = $common->testusername($_POST['uid']);
        }else{
            $project_user = $project->iflogin();
        }
        try{
            unset($where);
            $proWhere['id'] = $_POST['pro_id'];
            $proDetail = Db::name("project_pro")->where($proWhere)->find();
            $where["pro_id"]      = empty($proDetail['pid'])?$proDetail['id']:$proDetail['pid'];
            $where['type_id']     = empty($_POST['type_id'])?0:$_POST['type_id'];
            $data               = PublicService::detailService("project_pro_advance_plan",$where,1);
            $accountList = [];
            if(!empty($data["duty_unit"])){
                $duty_unit = explode(";",$data["duty_unit"]);
                foreach ($duty_unit as $k=>$v){
                    unset($where);
                    $where['name'] = $v;
                    $accountList[] = Db::name("project_dictionaries")->where($where)->field("id,name")->find();
                }
            }
            return buildSuccess($accountList);
        }catch (Exception $e){
            return buildError($e->getMessage());
        }
    }

    //服务单位添加
    public function addService(){
        $common = new Common();
        $project = new Project();
        if(!empty($_POST['uid'])){
            $project_user = $common->testusername($_POST['uid']);
        }else{
            $project_user = $project->iflogin();
        }
        try{
            $proId = empty($_POST['pro_id'])?0:$_POST['pro_id'];
            $proWhere['id'] = $proId;
            //判断是否是该项目负责人
            $proDetail = Db::name("project_pro")->where($proWhere)->find();
            $duty_person = explode(";",$proDetail['duty_person']);
            if(!in_array($project_user['name'],$duty_person)){
                throw new Exception("您不是该项目的负责人，不能进行操作");
            }
            //判断是否是该项目负责人end

            $where["pro_id"]      = empty($proDetail['pid'])?$_POST['pro_id']:$proDetail['pid'];
            $where['type_id']     = empty($_POST['type_id'])?0:$_POST['type_id'];
            $data               = PublicService::detailService("project_pro_advance_plan",$where,1);
            $addData['pro_id'] = empty($proDetail['pid'])?$proDetail['id']:$proDetail['pid'];;
            $addData['type_id'] = empty($_POST['type_id'])?0:$_POST['type_id'];;
            if(!empty($data)){
                $addData['id'] = $data['id'];
            }
            $accountList = empty($_POST['accountList'])?"":$_POST['accountList'];
            $accountList = json_decode($accountList);
            $accountList = array_column($accountList,"name");
            $accountList = implode(";",$accountList);
            $addData['duty_unit'] = $accountList;
            $addData['color'] = empty($data['color'])?0:$data['color'];
            AdvancePlanService::saveService($addData);
            return buildSuccess();
        }catch (Exception $e){
            return buildError($e->getMessage(),202);
        }
    }



}